<template>
  <el-dialog
    v-model="dialogVisible"
    title="常用工具管理"
    width="80%"
    :before-close="handleClose"
  >
    <div class="tools-management">
      <!-- QuickTools 卡片 -->
      <el-card class="tools-card">
        <template #header>
          <div class="card-header">
            <span class="header-title">智能体组件</span>
            <div class="header-actions">
              <div class="tool-select-container">
                <el-select 
                  v-model="selectedTool" 
                  placeholder="请选择工具" 
                  style="width: 200px;"
                  class="tool-select"
                  @visible-change="handleSelectOpen"
                  :loading="toolsLoading"
                >
                  <el-option
                    v-for="tool in availableTools"
                    :key="tool.id"
                    :label="`${tool.id}-${tool.name}`"
                    :value="tool"
                  >
                    <span>{{ tool.id }}-{{ tool.name }}</span>
                  </el-option>
                </el-select>
              </div>
              <el-button type="primary" @click="handleAdd('quickTools')" :loading="addLoading">添加</el-button>
            </div>
          </div>
        </template>
        <el-table :data="localQuickTools" style="width: 100%">
          <el-table-column prop="id" label="ID" width="120" align="center" />
          <el-table-column prop="name" label="名称" width="150" align="center" />
          <el-table-column label="图标" width="100" align="center">
            <template #default="{ row }">
              <el-icon><component :is="row.icon"></component></el-icon>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="描述" min-width="200" />
          <el-table-column label="操作" width="120" align="center">
            <template #default="{ row }">
              <el-button type="danger" size="small" @click="handleDelete('quickTools', row)" :loading="deleteLoading === row.id">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- MCPTools 卡片 -->
      <el-card class="tools-card">
        <template #header>
          <div class="card-header">
            <span>MCP组件</span>
            <el-button type="primary" @click="handleAdd('MCPTools')">添加</el-button>
          </div>
        </template>
        <el-table :data="localMcpTools" style="width: 100%">
          <el-table-column prop="id" label="ID" width="120" align="center" />
          <el-table-column prop="name" label="名称" width="150" align="center" />
          <el-table-column label="图标" width="100" align="center">
            <template #default="{ row }">
              <el-icon><component :is="row.icon"></component></el-icon>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="描述" min-width="200" />
          <el-table-column label="操作" width="120" align="center">
            <template #default="{ row }">
              <el-button type="danger" size="small" @click="handleDelete('MCPTools', row)" :loading="deleteLoading === row.id">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- WorkflowComponents 卡片 -->
      <el-card class="tools-card">
        <template #header>
          <div class="card-header">
            <span>工作流组件</span>
            <el-button type="primary" @click="handleAdd('workflowComponents')">添加</el-button>
          </div>
        </template>
        <el-table :data="localWorkflowComponents" style="width: 100%">
          <el-table-column prop="id" label="ID" width="120" align="center" />
          <el-table-column prop="name" label="名称" width="150" align="center" />
          <el-table-column label="图标" width="100" align="center">
            <template #default="{ row }">
              <el-icon><component :is="row.icon"></component></el-icon>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="描述" min-width="200" />
          <el-table-column label="操作" width="120" align="center">
            <template #default="{ row }">
              <el-button type="danger" size="small" @click="handleDelete('workflowComponents', row)" :loading="deleteLoading === row.id">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue';
import { ElMessage } from 'element-plus';

// 接收props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  quickTools: {
    type: Array,
    default: () => []
  },
  mcpTools: {
    type: Array,
    default: () => []
  },
  workflowComponents: {
    type: Array,
    default: () => []
  }
});

// 定义要发出的事件
const emit = defineEmits(['update:visible', 'add', 'edit', 'delete']);

// 本地数据
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
});

const parameterConfig = ref({ name: '', value: '' });
const documentBlock = ref('');
const selectedTool = ref(null);
const availableTools = ref([]);

// 加载状态
const toolsLoading = ref(false);
const addLoading = ref(false);
const deleteLoading = ref(null);

// 本地副本
const localQuickTools = ref([...props.quickTools]);
const localMcpTools = ref([...props.mcpTools]);
const localWorkflowComponents = ref([...props.workflowComponents]);

// 当props变化时更新本地数据
watch(() => props.quickTools, (newVal) => {
  localQuickTools.value = [...newVal];
}, { deep: true });

watch(() => props.mcpTools, (newVal) => {
  localMcpTools.value = [...newVal];
}, { deep: true });

watch(() => props.workflowComponents, (newVal) => {
  localWorkflowComponents.value = [...newVal];
}, { deep: true });

// 当对话框打开时加载工具列表
watch(() => dialogVisible.value, (isVisible) => {
  if (isVisible) {
    fetchAvailableTools();
  }
});

// 添加handleClose方法
const handleClose = (done) => {
  dialogVisible.value = false;
  done();
};

const handlePreview = (file) => {
  console.log('Preview file:', file);
};

const handleRemove = (file) => {
  console.log('Remove file:', file);
};

// 加载可用工具列表
const fetchAvailableTools = async () => {
  try {
    toolsLoading.value = true;
    const response = await fetch('/api/agents/tools/commonTools');
    if (!response.ok) {
      throw new Error('获取工具列表失败');
    }
    const data = await response.json();
    availableTools.value = data.unique_tools || [];
  } catch (error) {
    console.error('获取工具列表出错:', error);
    ElMessage.error('获取工具列表失败: ' + error.message);
  } finally {
    toolsLoading.value = false;
  }
};

// 处理选择框打开
const handleSelectOpen = (isOpen) => {
  if (isOpen) {
    fetchAvailableTools();
  }
};

// 添加处理方法
const handleAdd = async (type) => {
  if (type === 'quickTools' && selectedTool.value) {
    // 调用添加API
    try {
      addLoading.value = true;
      
      // 调用保存API
      const response = await fetch('/api/agents/tools/commonTools/save', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(selectedTool.value)
      });
      
      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.detail || '添加工具失败');
      }
      
      const data = await response.json();
      
      // 发送事件到父组件
      emit('add', { type, data: selectedTool.value });
      
      // 清空选择
      selectedTool.value = null;
      
      // 成功提示
      ElMessage.success('工具添加成功');
      
    } catch (error) {
      console.error('添加工具失败:', error);
      ElMessage.error('添加工具失败: ' + error.message);
    } finally {
      addLoading.value = false;
    }
  } else if (type === 'MCPTools') {
    // 创建一个新的MCP工具
    const newTool = {
      id: `mcp-${Date.now()}`,
      name: '新MCP工具',
      icon: 'Setting',
      description: '这是一个新的MCP工具',
      type: 'MCP'
    };
    
    try {
      addLoading.value = true;
      const response = await fetch(`/api/common/tools/${type}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(newTool)
      });
      
      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.detail || '添加MCP工具失败');
      }
      
      // 发送事件到父组件
      emit('add', { type, data: newTool });
      
      // 成功提示
      ElMessage.success('MCP工具添加成功');
      
    } catch (error) {
      console.error('添加MCP工具失败:', error);
      ElMessage.error('添加MCP工具失败: ' + error.message);
    } finally {
      addLoading.value = false;
    }
  } else if (type === 'workflowComponents') {
    // 创建一个新的工作流组件
    const newComponent = {
      id: `workflow-${Date.now()}`,
      name: '新工作流',
      icon: 'Document',
      description: '这是一个新的工作流组件'
    };
    
    try {
      addLoading.value = true;
      const response = await fetch(`/api/common/tools/${type}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(newComponent)
      });
      
      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.detail || '添加工作流组件失败');
      }
      
      // 发送事件到父组件
      emit('add', { type, data: newComponent });
      
      // 成功提示
      ElMessage.success('工作流组件添加成功');
      
    } catch (error) {
      console.error('添加工作流组件失败:', error);
      ElMessage.error('添加工作流组件失败: ' + error.message);
    } finally {
      addLoading.value = false;
    }
  }
};

const handleDelete = async (type, item) => {
  try {
    deleteLoading.value = item.id;
    
    // 调用删除API
    const response = await fetch(`/api/common/tools/${type}/${item.id}`, {
      method: 'DELETE'
    });
    
    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(errorData.detail || '删除工具失败');
    }
    
    // 发送事件到父组件
    emit('delete', { type, data: item });
    
    // 成功提示
    ElMessage.success('工具删除成功');
    
  } catch (error) {
    console.error('删除工具失败:', error);
    ElMessage.error('删除工具失败: ' + error.message);
  } finally {
    deleteLoading.value = null;
  }
};

// 组件挂载时，如果对话框是打开状态，则加载工具列表
onMounted(() => {
  if (dialogVisible.value) {
    fetchAvailableTools();
  }
});
</script>

<style scoped>
.configuration-section {
  display: flex;
  flex-direction: column;
  gap: 20px;
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  font-weight: bold;
}

.header-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.tools-card {
  margin-bottom: 20px;
}

.tools-management {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.tool-select-container {
  margin-right: 10px;
}
</style>